"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const defines_1 = require("../../lib/defines");
const Member_1 = require("../../lib/Member");
const Classrooms_1 = require("../../lib/Classrooms");
const utils_1 = require("../../utils/utils");
const log4js_1 = require("log4js");
const logger = (0, log4js_1.getLogger)('socket/adminUpdate');
function userLogin(app) {
    const { socket } = app.locals;
    const { userId, username } = socket.handshake.query;
    socket.on(defines_1.RequestMethod.login, async function ({ rooms, members }, cb) {
        logger.debug('-------------------->', defines_1.RequestMethod.login);
        const owner = { userId, username };
        let memberBroadcast = [];
        let classMember = Member_1.Members.get(userId);
        if (!classMember) {
            return cb && cb(socket.errorMsg('login', 'member not find!'));
        }
        if ((0, utils_1.isType)(rooms, 'array')) {
            rooms.forEach(({ classId }) => {
                const room = Classrooms_1.Classrooms.get(classId);
                classMember.setClassroom(classId);
                if (room) {
                    const __members = room.getMembers(true);
                    memberBroadcast = memberBroadcast.concat(__members);
                    socket.broadcast.to(classId).emit('member:online', owner);
                }
            });
        }
        if ((0, utils_1.isType)(members, 'array')) {
            members.forEach(({ userId }) => {
                classMember.setAudience(userId);
                const __member = Member_1.Members.get(userId);
                if (__member) {
                    if (Classrooms_1.Classrooms.has(__member.classId)) {
                        return;
                    }
                    const { userId, username, socketId } = __member;
                    logger.debug(`member:online: => { userId: ${userId}, username: ${username}, socketId: ${socketId} }`);
                    memberBroadcast.push(__member);
                    socket.to(socketId).emit('member:online', owner);
                }
            });
        }
        if (cb) {
            cb({
                status: 'ok',
                resolve: '[response]:logged',
                members: Member_1.Members.toArray(),
                broadcast: memberBroadcast
            });
        }
    });
}
exports.default = userLogin;
